<template>
  <el-dialog :visible="visible" :title="title" @close="close">
    <!-- 表单区域 -->
    <el-form ref="permissionRef" :model="permissionForm" :rules="permissionRules" label-width="80px">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="permissionForm.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="permissionForm.code" />
      </el-form-item>
      <el-form-item label="权限描述">
        <el-input v-model="permissionForm.description" />
      </el-form-item>
      <el-form-item label="权限启用">
        <el-switch
          v-model="permissionForm.enVisible"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <!-- 按钮区域 -->
    <template #footer>
      <div style="text-align: right;">
        <el-button @click="$emit('close')">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { addPermission, getPermissionDetail, updatePermission } from '@/api'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    pid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      permissionForm: {
        name: '', // 权限名称
        code: '', // 权限标识
        description: '', // 权限描述
        enVisible: '0', // 权限启用标识
        type: '', // 类型 区分当前是添加菜单权限点还是按钮权限点
        pid: '' // 添加到哪个节点下，权限点的父id
      },
      // 表单校验
      permissionRules: {
        name: [
          { required: true, message: '请填写权限名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请填写权限标识', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.permissionForm.id ? '编辑权限点' : '新增权限点'
    }
  },
  methods: {
    // 关闭表单
    // 通知父组件
    // 清空表单校验和内容
    close() {
      this.$emit('close')
      this.$refs.permissionRef.resetFields()
      this.permissionForm = {
        name: '',
        code: '',
        description: '',
        enVisible: '0',
        type: '',
        pid: ''
      }
    },

    // 点击确定提交
    // 进行兜底校验
    // 请求接口
    // 提示用户、关闭弹窗
    // 通知父组件刷新列表
    submit() {
      this.$refs.permissionRef.validate(async valid => {
        if (!valid) return
        if (this.permissionForm.id) {
          await updatePermission(this.permissionForm)
          this.$message.success('编辑权限点成功')
        } else {
          await addPermission({
            ...this.permissionForm,
            type: this.type,
            pid: this.pid
          })
          this.$message.success('添加权限点成功')
        }
        this.$emit('close')
        this.$emit('update')
      })
    },

    // 获取详情
    async getDetail(id) {
      const { data } = await getPermissionDetail(id)
      this.permissionForm = data
    }
  }
}
</script>

<style>

</style>
